package com.zjk.dao;

import com.zjk.domain.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhujinkai
 * @version 1.0
 * @date 2020/10/22 11:27
 */
/*JpaSpecificationExecutor<Blog>:能够实现动态的组合查询*/
public interface BlogRepository extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {

    @Query("select b from t_blog b where b.recommend = true")
    List<Blog> findTop(Pageable pageable);

    @Query("select b from t_blog b where b.title like ?1 or b.type.name like ?1 or b.content like ?1 or b.description like ?1")
    Page<Blog> findByQuery(String query, Pageable pageable);

    /**
     * 浏览次数更新
     * @param id
     * @return
     */
    @Transactional
    @Modifying
    @Query("update t_blog b set b.views = b.views+1 where b.id = ?1")
    int updateViews(Long id);

    @Query("select function('date_format', b.updateTime, '%Y%m') as yearMonth from t_blog b group by yearMonth order by function('date_format', b.updateTime, '%Y%m') desc")
    List<String> findGroupYearMonth();

    @Query("select b from t_blog b where function('date_format', b.updateTime, '%Y%m') = ?1")
    List<Blog> findByYearMonth(String yearMonth);
}
